//
//  MKSystemPreviewViewController.swift
//  MKImageBrowser3
//
//  Created by 劢克科技 on 2019/5/13.
//  Copyright © 2019 meckey. All rights reserved.
//
//  预览View Controller

import UIKit
import Photos

class MKSystemPreviewViewController: UIViewController {
    
    let cellIdentifier = "cellIdentifier"
    let videoCellIdentifier = "videoCellIdentifier"
    
    override var prefersStatusBarHidden: Bool {
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if fetchResult == nil {
            let allPhotoOptions = PHFetchOptions()
            allPhotoOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            fetchResult = PHAsset.fetchAssets(with: allPhotoOptions)
        }
        
        setupUI()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
    }
    
    //MARK: - Setter
    
    fileprivate var images = [UIImage]()
    fileprivate var orderImage = [[IndexPath: UIImage]]()
    var currentIndex = 0
    
    func setImages(images: [[IndexPath: UIImage]]) {
        for item in images {
            self.images.append(item.values.first!)
        }
        self.orderImage = images
    }
    
    //MARK: - getter
    
    fileprivate var fetchResult: PHFetchResult<PHAsset>!
    fileprivate let imageManager = PHImageManager()
    
    lazy var navView: UIView = {
        let view = UIView()
        view.backgroundColor = #colorLiteral(red: 0.2341118847, green: 0.2341118847, blue: 0.2341118847, alpha: 0.7531084947)
        return view
    }()
    
    lazy var backButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("返回", for: .normal)
        button.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
        button.addTarget(self, action: #selector(close), for: .touchUpInside)
        return button
    }()
    
    lazy var indexLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16)
        label.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        label.text = "(1/\(self.images.count))"
        return label
    }()
    
    lazy var collectionView: MKSystemPreviewCollectionView = {
        let collectionView = MKSystemPreviewCollectionView()
        collectionView.register(MKSystemPreviewCollectionViewCell.self, forCellWithReuseIdentifier: self.cellIdentifier)
        collectionView.register(MKSystemPreviewVideoCollectionViewCell.self, forCellWithReuseIdentifier: self.videoCellIdentifier)
        collectionView.dataSource = self
        collectionView.delegate = self
        return collectionView
    }()
    
    //MARK: - Events
    
    @objc fileprivate func close() {
        navigationController?.popViewController(animated: true)
    }
}

//MARK: - < CollectionView DataSource >

extension MKSystemPreviewViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let asset = fetchResult.object(at: orderImage[indexPath.item].keys.first!.item)
        if asset.mediaType == .video {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: videoCellIdentifier, for: indexPath) as! MKSystemPreviewVideoCollectionViewCell
            // 获取视频
            let options = PHVideoRequestOptions()
            options.deliveryMode = .automatic
            options.version = .current

            imageManager.requestAVAsset(forVideo: asset, options: options) { (avasset, _, _) in
                DispatchQueue.main.async {
                    let resAsset = avasset as! AVURLAsset
                    cell.setVideoUrl(url: resAsset.url)
                }
            }
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! MKSystemPreviewCollectionViewCell
            cell.setImage(image: images[indexPath.item])
            return cell
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let index = Int((scrollView.contentOffset.x + UIScreen.main.bounds.width / 2) / UIScreen.main.bounds.width)
        indexLabel.text = "(\(index + 1)/\(images.count))"
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        for cell in collectionView.visibleCells {
            if cell.isKind(of: MKSystemPreviewVideoCollectionViewCell.self) {
                (cell as! MKSystemPreviewVideoCollectionViewCell).pause()
            }
        }
    }
}

//MARK: - UI

extension MKSystemPreviewViewController {
    fileprivate func setupUI() {
        view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        
        view.addSubview(collectionView)
        view.addSubview(navView)
        navView.addSubview(backButton)
        navView.addSubview(indexLabel)
        
        navView.snp.makeConstraints { (make) in
            make.left.equalTo(view.snp.left)
            make.right.equalTo(view.snp_right)
            make.top.equalTo(view.snp_top)
            make.height.equalTo(64)
        }
        
        backButton.snp.makeConstraints { (make) in
            make.left.equalTo(navView.snp_left)
            make.top.equalTo(navView.snp_top)
            make.bottom.equalTo(navView.snp_bottom)
            make.width.equalTo(navView.snp_height)
        }
        
        indexLabel.snp.makeConstraints { (make) in
            make.right.equalTo(navView.snp_right)
            make.top.equalTo(navView.snp_top)
            make.bottom.equalTo(navView.snp_bottom)
            make.width.equalTo(navView.snp_height)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.top.equalTo(view.snp_top)
            make.bottom.equalTo(view.snp_bottom)
        }
    }
}
